package com.tank.nio;

import java.nio.ByteBuffer;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/8/4 0004
 * Time: 下午 9:59
 * To change this template use File | Settings | File Templates.
 */
public class NioTest4 {

    public static void main(String[] args) {
        //testPut();
        //testSlice();
        testAsReadOnlyBuffer();
    }

    public static  void testPut(){
        //buffer数组长度必须大于或等于存放数据字节数之和
        //获取buffer内容时必须按制定类型
        ByteBuffer byteBuffer = ByteBuffer.allocate(4+8+2);
        //4个字节
        byteBuffer.putInt(10);
        //8个字节
        byteBuffer.putDouble(2.02d);
        //2个字节
        byteBuffer.putChar('o');

        //反转
        byteBuffer.flip();
        System.out.println("int:"+byteBuffer.getInt());
        System.out.println("double:"+byteBuffer.getDouble());
        System.out.println("char:"+byteBuffer.getChar());
    }

    /**
     * sliceBuffer与原buffer共享数组，so sliceBuffer与buffer指向同一对象，其中任意引用对该数组
     * 的操作也会都反映到另一个引用上
     * Changes to this buffer's content will be visible in the new
     * buffer, and vice versa; the two buffers' position, limit, and mark
     * values will be independent
     */
    public static void testSlice(){

        ByteBuffer byteBuffer = ByteBuffer.allocate(10);

        for (int i = 0; i < byteBuffer.capacity(); i++) {
            byteBuffer.put((byte)i);
        }

        //首位
        byteBuffer.position(2);
        //限制
        byteBuffer.limit(6);
        ByteBuffer slice = byteBuffer.slice();

        for (int i = 0; i < slice.capacity(); i++) {
            byte b = slice.get(i);
            b *= 2;
            slice.put(i,b);
        }
        //重置
        byteBuffer.position(0);
        byteBuffer.limit(byteBuffer.capacity());
        while (byteBuffer.hasRemaining()){
            System.out.println( byteBuffer.get());
        }
    }

    /**
     * readOnlyBuffer与源buffer共享数组，buffer对数组内容的更新对于
     * readOnlyBuffer是可见的
     * but readOnlyBuffer却不能更新，方法直接抛出
     *  throw new ReadOnlyBufferException();
     */
    public static void testAsReadOnlyBuffer(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        for (int i = 0; i <byteBuffer.capacity() ; i++) {
            //最大值127
            byteBuffer.put((byte)i);
        }
        //byteBuffer.position(2);

        ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();
        readOnlyBuffer.position(0);
      //  byteBuffer.flip();
        while (readOnlyBuffer.hasRemaining()){
            System.out.println(readOnlyBuffer.get());
        }

        //修改readOnlyBuffer
        readOnlyBuffer.put(5,(byte) 55);
    }
}
